package com.cwz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cwz.entity.Literature;
import com.cwz.entity.LiteratureRecord;
import com.cwz.entity.Material;
import com.cwz.mapper.LiteratureMapper;
import com.cwz.param.LiteratureHttpQueryParam;
import com.cwz.param.LiteratureStatisticsParam;
import com.cwz.service.LiteratureService;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class LiteratureServiceImpl implements LiteratureService {

    @Resource
    private LiteratureMapper literatureMapper;

    @Override
    public Map<String, Object> save(Literature literature, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        // 实现保存逻辑
        log.info("保存文献: {}", literature.getTitle());
        literatureMapper.insert(literature);
        return success();
    }

    @Override
    public Map<String, Object> upload(MultipartFile file, HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        // 1. 检查文件是否为空
        if (file.isEmpty()) {
            result.put("success", false);
            result.put("message", "上传的文件为空");
            return result;
        }

        // 2. 获取文件名并记录日志
        String fileName = file.getOriginalFilename();
        log.info("文献文件: {}", fileName);

        try {
            // 3. 检查文件类型是否为 PDF
            if (!fileName.toLowerCase().endsWith(".pdf")) {
              throw new RuntimeException("仅支持PDF文件！");
            }

            // 4. 保存 PDF 文件
            String filePath = saveFileToServer(file);
            Literature literature = new Literature();
            literature.setFilePath(filePath);
            // 7. 返回成功结果
            return success(literature);
        } catch (Exception e) {
            // 8. 处理异常
            log.error("文件上传失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "文件上传失败: " + e.getMessage());
            return success(result);
        }

    }

    /**
     * 保存 PDF
     */
    private String saveFileToServer(MultipartFile file) throws IOException {
        // 1. 设置文件保存路径
        String uploadDir = "D:\\uploads\\"; // 文件保存目录
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs(); // 如果目录不存在，则创建
        }

        // 2. 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();

        // 3. 保存文件
        String filePath = uploadDir + fileName;
        File dest = new File(filePath);
        file.transferTo(dest);

        return filePath;
    }

    /**
     * 提取文献信息
     */
    private Literature extractLiteratureInfo(MultipartFile file, String filePath) {
        Literature literature = new Literature();

        // 1. 从文件名中提取标题（假设文件名是标题）
        String fileName = file.getOriginalFilename();
        String title = fileName.substring(0, fileName.lastIndexOf('.'));
        literature.setTitle(title);

        // 2. 设置其他字段（可以从表单或默认值中获取）
        literature.setAuthor("未知作者"); // 默认作者
        literature.setYear(String.valueOf(LocalDate.now().getYear())); // 默认当前年份
        literature.setFilePath(filePath); // 文件路径
        literature.setIsDisabled(false); // 默认不禁用
        literature.setCreateTime(LocalDateTime.now()); // 创建时间
        literature.setUpdateTime(LocalDateTime.now()); // 更新时间

        return literature;
    }

    @Override
    public Map<String, Object> page(LiteratureHttpQueryParam param, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        // 实现分页查询逻辑
        log.info("分页查询文献: 标题={}, 作者={}, 年份={}", param.getTitle(), param.getAuthor(), param.getYear());
        IPage<Literature> page = new Page<>(param.getPage(), param.getSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like(!StringUtils.isNullOrEmpty(param.getTitle()), "title", param.getTitle())
                .like(!StringUtils.isNullOrEmpty(param.getAuthor()), "author", param.getAuthor())
                .eq(!StringUtils.isNullOrEmpty(param.getYear()),"year",param.getYear());

        page = literatureMapper.selectPage(page, queryWrapper);
        return success(page);
    }

    @Override
    public Map<String, Object> disable(Integer id, HttpSession session) {

        // 实现禁用逻辑
        log.info("禁用文献: ID={}", id);
        literatureMapper.deleteById(id);
        return success("删除成功");
    }

    @Override
    public Map<String, Object> detail(Integer id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        // 实现详情查询逻辑
        log.info("查看文献详情: ID={}", id);
        result.put("code", 200);
        result.put("data", "文献详情");
        return result;
    }

    @Override
    public void download(Integer id, HttpServletResponse response) {
        try {
            // 1. 根据文献 ID 查询文献信息
            Literature literature = literatureMapper.selectById(id);
            if (literature == null) {
                throw new RuntimeException("文献不存在!");
            }

            // 2. 获取文件路径
            String filePath = literature.getFilePath();
            if (filePath == null || filePath.isEmpty()) {
                throw new RuntimeException("文件路径为空!");
            }

            // 3. 检查文件是否存在
            File file = new File(filePath);
            if (!file.exists()) {
                throw new RuntimeException("文件不存在!");
            }

            // 4. 设置响应头
            response.setContentType("application/pdf");
            String fileName = file.getName();
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString())
                    .replace("+", "%20"); // 替换空格编码
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);

            // 5. 将文件写入响应流
            try (InputStream inputStream = new FileInputStream(file);
                 OutputStream outputStream = response.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
                outputStream.flush();
            }
        } catch (Exception e) {
            // 6. 处理异常
            log.error("文件下载失败: {}", e.getMessage(), e);
            throw new RuntimeException("文件下载失败: " + e.getMessage());
        }
    }
    @Override
    public Map<String, Object> statistic(LiteratureStatisticsParam param, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        // 实现统计逻辑
        log.info("统计文献操作记录: 开始时间={}, 结束时间={}", param.getStartTime(), param.getEndTime());
        result.put("code", 200);
        result.put("data", "统计结果");
        return result;
    }
}